import os
import random
import re
import time
from datetime import datetime

import jwt
import redis
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from OA_pro import settings
from primary.models import UserModel, RoleModel, AccessModel, BranchModel, RankModel, FileMaterialsModel, MoneyBomModel, \
    SendEmailModel, ReceiveEmailModel, VehicleModel, ProcessModel, ProcessNodeModel, MenuModel, LoginLogModel, \
    OperationLogModel
from utils.chack_login import check_login
from utils.send_email2 import send_mail
from utils.sms_code_task import send_message


class SmsCodeView(APIView):
    def get(self, request):
        phone = request.query_params.get('phone')
        if not phone or not re.search(r'^1[3-9]\d{9}$', phone):
            return Response({'code': 400, 'msg': '手机号格式不匹配'})
        red = redis.Redis(host='127.0.0.1', port=6379)
        time_code = red.get('time_%s' % phone)
        if time_code:
            return Response({
                'code': 400, 'msg': '60秒内不能重复发送'
            })
        # 发送异步验证码
        resp = send_message.delay(phone)
        time.sleep(3)
        print(resp)
        return Response({'code': 200, 'msg': '验证码已发送'})


class LoginView(APIView):
    # 用户登录注册
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        if not all([phone, code]):
            return Response({
                'code': 400, 'msg': '注册信息不完整'
            })
        if not re.search(r'^1[3-9]\d{9}$', phone):
            return Response({
                'code': 400, 'msg': '手机号格式不正确'
            })
        red = redis.Redis(host='127.0.0.1', port=6379)
        red_code = red.get(phone)
        if not red_code:
            return Response({
                'code': 400, 'msg': '验证码已过期'
            })
        if code != red_code.decode():
            return Response({
                'code': 400, 'msg': '验证码错误'
            })
        user = UserModel.objects.filter(phone=phone).first()
        if not user:
            name = 'new_hand' + str(time.time())
            UserModel.objects.create(phone=phone, name=name)
        user = UserModel.objects.filter(phone=phone).first()
        payload = {
            'user_id': user.id,
            'phone': user.phone,
            'exp': time.time() + 7200
        }
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        return Response({
            'code': 200, 'msg': '登录成功',
            'token': token
        })

    # 用户退出登录
    def delete(self, request):
        token = request.headers.get('token')
        rds = redis.Redis(host='127.0.0.1', port=6379)
        rds.set('token_%s' % token, '1', ex=7200)
        rds.close()
        return Response({
            'code': 200, 'msg': '退出登录成功'
        })


# 用户上传头像
class UploadView(APIView):
    def post(self, request):
        file_img = request.FILES.get('file_img')
        if not file_img:
            return Response({
                'code': 400, 'msg': '没有接收到文件'
            })
        file_name = file_img.name  # 获取文件名
        # s = os.path.splitext(file_name)[0]  # 121645B2jAV
        # b = os.path.splitext(file_name)[1]  # .jpg
        suffix = file_name[file_name.rfind('.') + 1:]  # rfind获取文件后缀名
        filename = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
        filename += str(random.randint(10000, 99999))
        filename += '.'
        filename += suffix
        # 从配置文件中载入图片保存路径
        IMG_DIRS = settings.STATICFILES_DIRS
        img_path = os.path.join(IMG_DIRS[0], filename)
        # 写入文件到本地
        with open(img_path, 'ab') as f:
            # 如果上传的图片非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in file_img.chunks():
                f.write(chunk)
        key = 'static/' + filename
        return Response({
            'code': 200, 'msg': '上传成功',
            'data': {
                'filename': key
            }
        })


""" 用户管理 """


class UserInView(APIView):
    @check_login
    def get(self, request):
        print('11')
        return Response({
            'code': 200, 'msg': '测试路由，有权访问'
        })


class UserInfoView(APIView):
    # 新增用户
    @check_login
    def post(self, request):
        name = request.data.get('user_name')
        root = request.data.get('root')
        phone = request.data.get('phone')
        role_id = request.data.get('role_id')
        branch_id = request.data.get('branch_id')
        rank_id = request.data.get('rank_id')
        if not all([name, root, phone, role_id, branch_id, rank_id]):
            return Response({
                'code': 400, 'msg': '参数不完整'
            })
        UserModel.objects.create(user_name=name, root=root, phone=phone, role_id=role_id,
                                 branch_id=branch_id, rank_id=rank_id)
        return Response({
            'code': 200, 'msg': '新增用户成功'
        })

    # 查看所有用户信息
    @check_login
    def get(self, request):
        info_all = UserModel.objects.all()
        info_list = []
        for info in info_all:
            dic = {
                'name': info.name,
                'root': info.root,
                'phone': info.phone,
                'role_id': info.role_id,
                'branch_id': info.branch_id,
                'rank_id': info.rank_id,
            }
            info_list.append(dic)
        return Response({
            'code': 200, 'data': info_list
        })


class UserInfoView2(APIView):
    # 查看某用户
    @check_login
    def get(self, request):
        phone = request.query_params.get('phone')
        info = UserModel.objects.filter(phone=phone).first()
        if not info:
            return Response({
                'code': 400, 'msg': '查无此人'
            })
        dic = {
            'name': info.name,
            'root': info.root,
            'phone': info.phone,
            'role_id': info.role_id,
            'branch_id': info.branch_id,
            'rank_id': info.rank_id,
        }
        return Response({
            'code': 400, 'data': dic
        })

    # 删除
    @check_login
    def delete(self, request):
        user_id = request.data.get('user_id')
        UserModel.objects.filter(id=user_id).delete()
        return Response({
            'code': 400, 'msg': '删除成功'
        })

    # 修改
    @check_login
    def put(self, request):
        user_id = request.data.get('user_id')
        name = request.data.get('name')
        root = request.data.get('root')
        phone = request.data.get('phone')
        role_id = request.data.get('role_id')
        branch_id = request.data.get('branch_id')
        rank_id = request.data.get('rank_id')
        info = UserModel.objects.filter(id=user_id).first()
        info.name = name
        info.root = root
        info.phone = phone
        info.role_id = role_id
        info.branch_id = branch_id
        info.rank_id = rank_id
        info.save()
        return Response({
            'code': 400, 'msg': '修改成功'
        })


""" 部门管理"""

# 添加部门
class BranchView(APIView):
    @check_login
    def post(self, request):
        name = request.data.get('branch_name')
        if not all([name]):
            return Response({
                'code': 400, 'msg': '参数不完整'
            })
        UserModel.objects.create(branch_name=name)
        return Response({
            'code': 200, 'msg': '新增用户成功'
        })

    # 查看所有部门信息
    @check_login
    def get(self, request):
        info_all = BranchModel.objects.all()
        info_list = []
        for info in info_all:
            dic = {
                'name': info.name,
            }
            info_list.append(dic)
        return Response({
            'code': 200, 'data': info_list
        })


# 查看单独的部门
class BranchInfoView(APIView):
    @check_login
    def get(self,request):
        name = request.query_params.get('branch_name')
        info = BranchModel.objects.filter(branch_name=name).first()
        if not info:
            return Response({
                'code': 400,
                'msg': '没有此部门'
            })
        dic = {
            'name': info.branch_name
        }
        return  Response({
            'code': 400,
            'data': dic
        })

    # 删除
    @check_login
    def delete(self, request):
        branch_id = request.data.get('branch_id')
        BranchModel.objects.filter(id=branch_id).delete()
        return Response({
            'code': 400, 'msg': '删除成功'
        })

    # 修改
    @check_login
    def put(self, request):
        branch_id = request.data.get('branch_id')
        branch_name = request.data.get('branch_name')
        info = UserModel.objects.filter(id=branch_id).first()
        info.name = branch_name
        info.save()
        return Response({
            'code': 400, 'msg': '修改成功'
        })


"""权限管理"""


# 添加权限
class AccView(APIView):
    @check_login
    def post(self,request):
        access_name = request.data.get('access_name')
        access_path = request.data.get('access_path')
        access_method = request.data.get('access_method')
        if not all([access_name,access_path,access_method]):
            return Response({
                'code': 400,
                'msg': "参数错误"
            })
        AccessModel.objects.create(access_name=access_name,access_path=access_path,access_method=access_method)
        return Response({
            'code': 200, 'msg': '新增用户成功'
        })

# 查看所有权限
    @check_login
    def get(self, request):
        info_all = AccessModel.objects.all()
        info_list = []
        for info in info_all:
            dic = {
                'name': info.access_name,
                'path': info.access_path,
                'method': info.access_method,
            }
            info_list.append(dic)
        return Response({
            'code': 200, 'data': info_list
        })


# 删除权限
class DelAccView(APIView):
    # 删除
    @check_login
    def delete(self, request):
        role_id = request.data.get('role_id')
        AccessModel.objects.filter(id=role_id).delete()
        return Response({
            'code': 400, 'msg': '删除成功'
        })

    # 修改
    @check_login
    def put(self, request):
        role_id = request.data.get('role_id')
        name = request.data.get('access_name')
        path = request.data.get('access_path')
        method = request.data.get('access_method')
        info = AccessModel.objects.filter(id=role_id).first()
        info.name = name
        info.path = path
        info.method = method
        info.save()
        return Response({
            'code': 400, 'msg': '修改成功'
        })


"""职级管理"""


# 添加职级
class RankView(APIView):
    @check_login
    def post(self,request):
        rank_name = request.data.get('rank_name')
        if not all([rank_name]):
            return Response({
                'code': 400,
                'msg': "参数错误"
            })
        RankModel.objects.create(rank_name=rank_name)
        return Response({
            'code': 200, 'msg': '新增用户成功'
        })

# 查看所有职级
    @check_login
    def get(self, request):
        info_all = RankModel.objects.all()
        info_list = []
        for info in info_all:
            dic = {
                'name': info.rank_name,
            }
            info_list.append(dic)
        return Response({
            'code': 200, 'data': info_list
        })


# 删除职级
class DelRaknView(APIView):
    # 删除
    @check_login
    def delete(self, request):
        rank_id = request.data.get('rank_id')
        RankModel.objects.filter(id=rank_id).delete()
        return Response({
            'code': 400, 'msg': '删除成功'
        })

    # 修改
    @check_login
    def put(self, request):
        role_id = request.data.get('role_id')
        name = request.data.get('access_name')
        info = RankModel.objects.filter(id=role_id).first()
        info.name = name
        info.save()
        return Response({
            'code': 400, 'msg': '修改成功'
        })


""" 角色管理"""


class RoleView(APIView):
    # 添加角色
    @check_login
    def post(self, request):
        role_name = request.data.get('role_name')
        if not all([role_name]):
            return Response({
                'code': 400,
                'msg': "参数错误"
            })
        RoleModel.objects.create(role_name=role_name)
        return Response({
            'code': 200, 'msg': '新增用户成功'
        })

    # 查看所有角色
    @check_login
    def get(self, request):
        info_all = RoleModel.objects.all()
        info_list = []
        for info in info_all:
            dic = {
                'name': info.role_name,
            }
            info_list.append(dic)
        return Response({
            'code': 200, 'data': info_list
        })


# 删除角色
class DelRoleView(APIView):
    # 删除
    @check_login
    def delete(self, request):
        rank_id = request.data.get('rank_id')
        RoleModel.objects.filter(id=rank_id).delete()
        return Response({
            'code': 400, 'msg': '删除成功'
        })

    # 修改
    @check_login
    def put(self, request):
        role_id = request.data.get('role_id')
        name = request.data.get('role_name')
        info = RoleModel.objects.filter(id=role_id).first()
        info.name = name
        info.save()
        return Response({
            'code': 400, 'msg': '修改成功'
        })


""" 文件材料表 """


class FileMaterialsView(APIView):
    @check_login
    def post(self, request):
        vehicle_type = request.data.get('vehicle_type')
        user_id = request.data.get('user_id')
        file_address = request.data.get('file_address')
        file_state = request.data.get('file_state')
        FileMaterialsModel.objects.create(vehicle_type=vehicle_type, file_address=file_address,
                                          file_state=file_state, user_id=user_id)
        return Response({
            'code': 200, 'msg': '添加资料成功'
        })

    @check_login
    def get(self, request):
        r = FileMaterialsModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'vehicle_type': i.vehicle_type,
                'user_id': i.user_id,
                'create_time': i.create_time,
                'file_address': i.file_address,
                'file_state': i.file_state,
            }
            r_list.append(dic)
        return Response({
            'code': 200, 'msg': '加载全部数据'
        })


""" 车辆信息管理 """


class VehicleView(APIView):
    @check_login
    def post(self,request):
        vehicle_type = request.data.get("vehicle_type")
        vehicle_number = request.data.get("vehicle_number")
        vehicle_state = request.data.get("vehicle_state")
        VehicleModel.objects.create(vehicle_type=vehicle_type,vehicle_number=vehicle_number,
                                    vehicle_state=vehicle_state)
        return Response({
            'code':200,
            'msg': "添加成功"
        })

    @check_login
    def get(self, request):
        r = VehicleModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'vehicle_type': i.vehicle_type,
                'vehicle_number': i.vehicle_number,
                'vehicle_state': i.vehicle_state,
            }
            r_list.append(dic)
        return Response({
            'code': 200, 'msg': '加载全部数据'
        })


""" 发送邮件 """


class SendEmailView(APIView):
    @check_login
    def post(self, request):
        send_email = request.data.get('send_address')
        send_title = request.data.get('send_title')
        harvest_email = request.data.get('harvest_email')
        content = request.data.get('content')
        user = UserModel.objects.filter(email=harvest_email).first()
        if send_title != request.user.email:
            return Response({
                'code': 400, 'msg': '请填写您绑定的邮箱'
            })
        if not harvest_email:
            return Response({
                'code': 400, 'msg': '邮件标题不能为空'
            })
        if not user:
            return Response({
                'code': 400, 'msg': '用户不是该公司员工'
            })
        SendEmailModel.objects.create(user=request.user, send_address=send_email, send_title=send_title,
                                      receive_id=user.id, content=content)
        try:
            send_mail(send_email, harvest_email, send_title, content)
            send_user = SendEmailModel.objects.filter(user=request.user).order_by('-id').first()
            # 发送成功同时 创建收件箱信息
            ReceiveEmailModel.objects.create(user_id=send_user.receive_id, send_email=send_user.user_id,
                                             receive_id=send_user.id, harvest_title=send_user.send_title,
                                             harvest_content=send_user.content)
            return Response({
                'code': 200, 'msg': '邮件发送成功'
            })
        except Exception as e:
            print(e)
            return Response({
                'code': 400, 'msg': '邮件发送失败'
            })


""" 工资单 """


class MoneyBomView(APIView):
    @check_login
    def post(self, request):
        user_id = request.data.get('user_id')
        work_day = request.data.get('work_day')
        absenteeism_day = request.data.get('absenteeism_day')
        rest_day = request.data.get('rest_day')
        basic_money = request.data.get('basic_money')
        rank_money = request.data.get('rank_money')
        FileMaterialsModel.objects.create(user_id=user_id, work_day=work_day, absenteeism_day=absenteeism_day,
                                          rest_day=rest_day, basic_money=basic_money, rank_money=rank_money)
        return Response({
            'code': 200, 'msg': '添加工资成功'
        })

    @check_login
    def get(self, request):
        r = MoneyBomModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'user_id': i.user_id,
                'work_day': i.work_day,
                'absenteeism_day': i.absenteeism_day,
                'rest_day': i.rest_day,
                'basic_money': i.basic_money,
                'rank_money': i.rank_money,
            }
            r_list.append(dic)
        return Response({
            'code': 200, 'msg': '加载全部数据'
        })


""" 流程引擎 """


class ProcessView(APIView):
    @check_login
    def post(self, request):
        pc_name = request.data.get("pc_name")
        create_time = request.data.get("create_time")
        is_valid = request.data.get("is_valid")
        ProcessModel.objects.create(pc_name=pc_name, create_time=create_time, is_valid=is_valid,)

        return Response({
            'code': 200, 'msg': '添加工资成功'
        })

    @check_login
    def get(self, request):
        r = ProcessModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'pc_name': i.pc_name,
                'create_time': i.create_time,
                'is_valid': i.is_valid,

            }
            r_list.append(dic)
        return Response({
            'code': 200, 'msg': '加载全部数据'
        })


"""流程节点"""


class ProcessNodeView(APIView):
    @check_login
    def post(self,request):
        process = request.data.get("process")
        process_node = request.data.get("process_node")
        ProcessNodeModel.objects.create(process=process,process_node=process_node)
        return Response({
            'code': 200,
            'msg': "添加成功"
        })

    @check_login
    def get(self,request):
        r = ProcessNodeModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'process': i.process,
                'process_node': i.process_node,
            }
            r_list.append(dic)
        return Response({
            'code': 200, 'msg': '加载全部数据'
        })


"""菜单管理"""


class MenuView(APIView):
    @check_login
    def post(self,request):
        menu_name = request.data.get("menu_name")
        MenuModel.objects.create(menu_name=menu_name)
        return Response({
            'code': 200,
            'msg': "添加成功"
        })

    @check_login
    def get(self,request):
        r = MenuModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'menu_name': i.menu_name,
            }
            r_list.append(dic)
        return Response({
            'code': 200,
            'msg': '加载全部数据'
        })


""" 日志"""


class LoginLogView(APIView):
    @check_login
    def post(self,request):
        user = request.data.get("user")
        end_time = request.data.get("end_time")
        login_device = request.data.get("login_device")
        login_ip = request.data.get("login_ip")
        login_address = request.data.get("login_address")
        LoginLogModel.objects.create(user=user,end_time=end_time,login_device=login_device,
                                     login_ip=login_ip,login_address=login_address)
        return Response({
            "code": 200,
            "msg": "添加成功"
        })

    @check_login
    def get(self, request):
        r = LoginLogModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                'user': i.user,
                'end_time': i.end_time,
                'login_device': i.login_device,
                'login_ip': i.login_ip,
                'login_address': i.login_address
            }
            r_list.append(dic)
        return Response({
            'code': 200,
            'msg': '加载全部数据'
        })


class OperationView(APIView):
    @check_login
    def post(self,request):
        user = request.data.get("user")
        action = request.data.get("action")
        OperationLogModel.objects.create(user=user, action=action)
        return Response({
            'code': 200,
            'msg': "添加成功 "
        })

    @check_login
    def get(self,request):
        r= OperationLogModel.objects.all()
        r_list = []
        for i in r:
            dic = {
                "user": i.user,
                "action": i.action
            }
            r_list.append(dic)
        return Response({
            'code': 200,
            'msg': 'ok'
        })



